package com.tanhua.dubbo.api.mongo;

import com.tanhua.model.mongo.Option;
import com.tanhua.model.mongo.Question;
import com.tanhua.model.mongo.Questionnaire;
import com.tanhua.model.mongo.Soul;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@DubboService
@Slf4j
public class SoulApiImpl implements SoulApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 根据人格类型和性别查询用户ids
     *
     * @param personalityType 人格类型
     * @param newGender       性别
     * @param level
     * @return 用户ids
     */
    @Override
    public List<Soul> findSoulUserIdByType(Integer personalityType, String newGender, Integer level) {
        Query query = new Query();
        query.addCriteria(Criteria.where("personalityType").is(personalityType).and("gender").is(newGender).and("level").is(level));
        return mongoTemplate.find(query, Soul.class);
    }

    /**
     * 根据报告id查询灵魂(鉴定)表soul
     *
     * @param reportId
     * @return
     */
    @Override
    public Soul findById(String reportId) {
        return mongoTemplate.findById(new ObjectId(reportId), Soul.class);
    }

    /**
     * 获取所有选项
     */

    @Override
    public List<Option> getOptionsList() {
        return mongoTemplate.findAll(Option.class);
    }

    /**
     * 获取所有问题
     */
    @Override
    public List<Question> getQuestionList() {
        return mongoTemplate.findAll(Question.class);
    }

    /**
     * 获取所有问卷
     */
    @Override
    public List<Questionnaire> getQuestionnaireList() {
        return mongoTemplate.findAll(Questionnaire.class);
    }

    /**
     * 通过结果id获取测试结果
     * @return
     */
    @Override
    public Map<Integer, ObjectId> getResultByUserId(Long userId) {
        HashMap<Integer, ObjectId> map = new HashMap<>();
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId)).with(Sort.by(Sort.Direction.DESC, "created"));
        List<Soul> one = mongoTemplate.find(query, Soul.class);
        if (one != null) {
            for (Soul soul : one) {
                map.put(soul.getLevel(),soul.getId());
            }
            return map;
        }
        return null;
    }
}
